#include <QtGui>
#include "serialport.h"
#include "osint.h"

#if defined(Q_WS_WIN32)
#include "osint_mingw.c"
#else
#include "osint_linux.c"
#endif

SerialPort::SerialPort()
{
    bytes = 0;
    isopen = false;
}
SerialPort::~SerialPort()
{
    isopen = false;
}

bool SerialPort::isOpen()
{
    return isopen;
}

void SerialPort::init(QString portname, int baudrate)
{
    portName = portname;
    baudRate = baudrate;
}

bool SerialPort::open(void)
{
    if(::serial_init(portName.toAscii(), baudRate)) {
        isopen = true;
    }
    return isopen;
}

bool SerialPort::close(void)
{
    if(isopen) {
        isopen = false;
        ::serial_done();
    }
    return isopen;
}

int  SerialPort::read(char *buffer, int length)
{
    return ::serial_rx_timeout(buffer, length, 100);
}

int  SerialPort::send(const char *buffer, int length)
{
    return ::serial_tx(buffer, length);
}

int  SerialPort::getHandle(void)
{
    return ::serial_handle();
}

int  SerialPort::bytesAvailable(void)
{
    if(isopen != true)
        return 0;
    return ::serial_bytes_available();
    //return (head == tail) ? 0 : 1;
#if 0
    int length = ::serial_rx_timeout(buffer,PORT_QSIZE,10);
    if(length > 0) {
        mutex.lock();
        barry.append(buffer,length);
        bytes += length;
        mutex.unlock();
    }
    return bytes;
#endif
}

int  SerialPort::getByte(char *ch)
{
    if(bytes > 0) {
        mutex.lock();
        *ch = barry.at(0);
        barry.remove(0,1);
        bytes--;
        if((bytes % 1000) == 0) qDebug() << bytes;
        mutex.unlock();
        return 1;
    }
    return 0;
}

QByteArray *SerialPort::readAll()
{
    char buffer[256];
    int length = ::serial_rx_timeout(buffer, 32, 100);
    mutex.lock();
    barry.append(buffer,length);
    mutex.unlock();
    return &barry;
}

